package com.xjmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.xjmall.common.ResponseCode;
import com.xjmall.common.ServerResponse;
import com.xjmall.dao.CommentMapper;
import com.xjmall.pojo.Comment;
import com.xjmall.service.ICommentService;
import com.xjmall.util.DateTimeUtil;
import com.xjmall.util.PropertiesUtil;
import com.xjmall.vo.CommentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by An on 2017/8/13.
 */
@Service
public class CommentServiceImpl implements ICommentService {

    @Autowired
    private CommentMapper commentMapper;
    /**
     * 根据商品id分页查询该商品所有评论
     * @param productId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ServerResponse<PageInfo> selectByProductId(Integer productId, int pageNum, int pageSize) {
        // 商品id非空校验
        if (productId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Comment> commentList = commentMapper.selectByProductId(productId);
        PageInfo pageInfo = new PageInfo(commentList);
        List<CommentVo> voList = Lists.newArrayList();
        for (Comment comment : commentList) {
            CommentVo vo = assembleCommentVo(comment);
            voList.add(vo);
        }
        pageInfo.setList(voList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 组装CommentVo
     * @param comment
     * @return
     */
    private CommentVo assembleCommentVo(Comment comment) {
        CommentVo result = new CommentVo();
        result.setId(comment.getId());
        result.setProductSpecName(comment.getProductSpecName());
        result.setCommentText(comment.getCommentText());
        result.setCommentType(comment.getCommentType());
        result.setCommentTime(DateTimeUtil.dateToStr(comment.getCommentTime()));
        result.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://127.0.0.1:8080/"));
        result.setUserAvatar(comment.getUserAvatar());
        if (comment.getIsanonymous() == 1) {
            result.setUsername(comment.getUsername().substring(0, 2) + "***");
        } else if (comment.getIsanonymous() == 0){
            result.setUsername(comment.getUsername());
        }
        return result;
    }
}
